<template>
  <div>
    <el-button @click="print" :loading="loading" type="primary">开始打印 {{defaultData.length}} 条</el-button>
    <el-checkbox v-model="checked" label="重点运动员" border></el-checkbox>
    <el-input v-model="pdfNum" style="width: 200px;"></el-input>
    <div id="playerDetailPrint" style="padding:50px 50px 50px 50px;overflow: visible;width: 900px;">
      <totalPrintOne :printData="printData" :usageId="3" :analysisReport="true"/>
    </div>
  </div>
</template>

<script>
  import html2Canvas from 'html2canvas'
  import JsPDF from 'jspdf'
  // import VueHtml2pdf from 'vue-html2pdf'
  import { dailyReportDefault,generate_daily_report } from '@/api/meta.js'
  import totalPrintOne from '@/components/print/totalPrintOne.vue'
  export default {
    components: {totalPrintOne},
    data() {
      return {
        printData: {},
        defaultData: [],
        list: [],
        fileName: '',
        download: false,
        pdfSave: 1,
        pdfNum: 0,
        checked: false,
        loading: false,
      }
    },
    computed: {
      pdfOptions() {
        return {
          margin: [0, 5, 0, 5],
          pagebreak: { mode: 'avoid-all'}
        }
      },
    },
    created() {
      this.pdfNum = window.localStorage.getItem('pdfNum') || 0
      this.pdfNum = parseInt(this.pdfNum)
      this.getDataList()
    },
    watch: {
      checked(val) {
        if(val){
          // let playerArr = [45511,45524,45530,45466,45484,45489,45497,45558,45566,45568,45609,45620,45621,45630,45815,45816,45820,45686,45690,45693,45676,45679,45780,45779,45772,45771,45878,45881,45883,45898,47414,47415,45719,45722,45724,45728,45796,45732,45735,45888,45889,45890,45500,45505,45527,45482,45488,47434,45561,45564,47265,45612,45625,45626,45627,45631,45633,45830,45687,45695,45669,47332,47333,47341,45748,45747,45755,45749,45753,45899,45892,45901,45528,45477,45912,45591,45592,45696,45697,47328,47330,45754,45763,45758,45905,45795,45797,45738,45902,45515,45521,45542,45578,45579,47264,45639,45641,47359,47598,45923,47521,45597,45602,45606,47526,47544,45904,47427,47432,45798,45734,45903,45913,47574,47573,47572,45526,45468,45486,47453,45925,47412,47492,47497,47527,45603,47537,47547,45711,47435,45741]
          let playerArr = [45592,45597,45602,45603]
          // let createDate = ['2020-09-14','2020-10-12','2020-11-09','2020-12-14','2021-01-11','2021-03-15','2021-04-12','2021-05-17','2021-06-12','2021-07-19','2021-08-23']
          let yearArr = ['2021']
          let arr = []
          this.list.forEach(item=>{
            let year = item.createDate.split('-')[0]
            if(playerArr.indexOf(parseInt(item.playerId))>-1 && item.templateId == 82 && yearArr.indexOf(year) > -1){
              arr.push(item)
            }
          })
          this.defaultData = arr
        }else{
          this.defaultData = this.list
        }
        console.log(this.defaultData)
      },
      // pdfSave(val){
      //   this.pdfNum += 1

      // }
    },
    methods: {
      cultureResultReturned(name) {
        this.fileName = name
      },
      print() {
        window.localStorage.setItem('pdfNum',this.pdfNum)
        if(this.defaultData.length==0){
          this.$message.error('没有数据怎么打印？！！！')
          return
        }
        if(this.pdfNum!=this.defaultData.length){
          this.playerDetailPrint(this.defaultData[this.pdfNum])
        }
      },
      playerDetailPrint(item) {
        let data = {
          playerID: item.playerId,
          usageID: 3,
          scenarioID: item.scenarioId,
          templateID: item.templateId,
          createDate: item.createDate + ' 00:00:00',
          startTime: '1970-01-01 00:00:00',
          endTime: '1970-01-01 00:00:00',
          packageIDs: item.packageIds,
          metaIDs: item.metaIds,
        }
        generate_daily_report(data).then(res=>{
          if(res.code === 200) {
            this.printData = res.data
          }
        }).then(()=>{
          let dom = document.getElementById('playerDetailPrint')
          this.getPdfFromHtml(dom,item.coachName+'教练-'+item.playerName+'-'+item.createDate+'机能日常报告')
        })
      },
      getDataList() {
        let data = {
          usageId: 3,
          type: 'search',
          invalidateCache: true,
        }
        this.loading = true
        dailyReportDefault(data).then(res=>{
          if(res.code === 200 && res.data.length!=0) {
            this.defaultData = res.data
            this.list = res.data
          }else{
            this.defaultData = []
          }
          this.loading = false
        })
      },
      getPdfFromHtml(ele, pdfFileName) {
            html2Canvas(ele,{
              dpi: window.devicePixelRatio * 4,
              scale: 4,
              useCORS: true,//允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
              allowTaint: false,
              height: ele.offsetHeight,
              width: ele.offsetWidth,
              windowWidth: document.body.scrollWidth,
              windowHeight: document.body.scrollHeight,
            }).then(canvas=>{
              this.dialogVisible = true;
              const _this = this;
              //未生成pdf的html页面高度
              var leftHeight = canvas.height;
              var a4Width = 595.28
              var a4Height = 841.89
              //一页pdf显示html页面生成的canvas高度;
              var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height);

              //pdf页面偏移
              var position = 0;

              var pageData = canvas.toDataURL('image/jpeg', 1.0);

              var pdf = new JsPDF('x', 'pt', 'a4');
              var index = 1,
                canvas1 = document.createElement('canvas'),
                height;
              pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');

              // $('.head-content').append($(
              //   '<div class="pdfTip">' +
              //   '   <div>正在生成第<span class="pdfProgress">1</span>页，共<span class="pdfTotal"></span>页...' +
              //   '</div>'));
              function createImpl(canvas) {
                if (leftHeight > 0) {
                  index++;
                  var checkCount = 0;
                  if (leftHeight > a4HeightRef) {
                    var i = position + a4HeightRef;
                    for (i = position + a4HeightRef; i >= position; i--) {
                      var isWrite = true
                      for (var j = 0; j < canvas.width; j++) {
                        var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data

                        if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
                          isWrite = false
                          break
                        }
                      }
                      if (isWrite) {
                        checkCount++
                        if (checkCount >= 10) {
                          break
                        }
                      } else {
                        checkCount = 0
                      }
                    }
                    height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
                    if(height<=0){
                      height = a4HeightRef;
                    }
                  } else {
                    height = leftHeight;
                  }

                  canvas1.width = canvas.width;
                  canvas1.height = height;

                  // console.log(index, 'height:', height, 'pos', position);

                  var ctx = canvas1.getContext('2d');
                  ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height);

                  var pageHeight = Math.round(a4Width / canvas.width * height);
                  // pdf.setPageSize(null, pageHeight)
                  if(position != 0){
                    pdf.addPage();
                  }
                  pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 20, a4Width, a4Width / canvas1.width * height);
                  leftHeight -= height;
                  position += height;
                  // $('.pdfProgress').text(index + 1);
                  // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
                  if (leftHeight > 0) {
                    //添加全屏水印
                    // const base64 = ''
                    // for(let i=0;i<6;i++){
                    //   for(let j=0;j<5;j++){
                    //     const  left = (j*120)+20;
                    //     pdf.addImage(base64,'JPEG', left, i*150, 20, 30);
                    //   }
                    // }
                    setTimeout(createImpl, 500, canvas);
                  } else {
                    // _this.iframeSrc = pdf.output('dataurlstring');
                    // debugger;
                    this.pdfSave = pdf.save(pdfFileName + '.pdf');
                  }
                }
              }

              //当内容未超过pdf一页显示的范围，无需分页
              if (leftHeight < a4HeightRef) {
                pdf.addImage(pageData, 'JPEG', 0, 0, a4Width, a4Width / canvas.width * leftHeight);
                this.dialogVisible = true;
                // this.iframeSrc = pdf.output('dataurlstring');
                // debugger;
                this.pdfSave = pdf.save(pdfFileName + '.pdf')
              } else {
                try {
                  pdf.deletePage(0);
                  // $('.pdfTip').show();
                  // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
                  setTimeout(createImpl, 500, canvas);

                } catch (err) {
                  console.log(err);
                }
              }
            }).then(()=>{
              this.pdfNum = parseInt(this.pdfNum)
              this.pdfNum += 1
            }).then(()=>{
              this.print()
            })

          },
    }
  }
</script>

<style scoped>

</style>
